<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 示例接口
 */
class Books extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    public function category()
    {
        $level = $this->request->param('level',1);
        $pid   = $this->request->param('pid');
        $category_model = new \app\admin\model\Bookscategory();
        $where['level'] = $level;
        if($pid){
            $where['pid'] = $pid;
        }
        $list = $category_model->where($where)->select();
        if($list){
            $list = collection($list)->toArray();
        }
        $data = [];
        foreach ($list as $val){
            $data[] = [
                'id' => $val['id'],
                'name' => $val['name'],
                'images' => cdnurl($val['images']),
            ];
        }
        $this->success('返回成功', $data);
    }

    public function books(){
        $category_id = $this->request->param('category_id');
        $title       = $this->request->param('title');
        $page        = $this->request->param('page');
        $books_model = new \app\admin\model\Books();
        if($category_id){
            $where['category_id'] = ['=',$category_id];
        }
        if($title){
            $where['title'] = ['like' , '%' . $title . '%' ];
        }
        $list = $books_model->where($where)
            ->page($page,10)
            ->order(['weigh'=>'desc','createtime'=>'DESC'])
            ->paginate()
            ->toArray();
        if(isset($list['data'])){
            $data = [];
            foreach ($list['data'] as $val){
                $data[] = [
                    'id' => $val['id'],
                    'title' => $val['title'],
                    'images' => cdnurl($val['url']),
                ];
            }
            $list['data'] = $data;
        }

        $this->success('返回成功', $list);
    }


}
